<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 东东
 */
class DongdongController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();

        switch($this->config['paytype']) {
            //支付宝
            case 3:
            case 4:
                if($isMobile){
                    $data['action'] = 'AliSao';
                }else{
                    $data['action'] = 'AliSao';
                }
                break;
            default:
                $this->showmessage('暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['txnamt'] = strval(intval($return['amount']*100));

        $data['merid'] = $this->config['mch_id'];
        $data['orderid'] = $return['orderid'];
        $data['backurl'] = $return['notifyurl'];
        $data['fronturl'] = $return['callbackurl'];
        //$data['ip'] = getIP();

        //$json = json_encode($data);
        $json = json_encode($data,JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

        $str = base64_encode($json) . $this->config['signkey'];

        $post = [];
        $post['req'] = base64_encode($json);
        $post['sign'] = md5($str);

        //https://api.hbasechina.org/api/mpgateway
        $res = curl($this->config['gateway'], httpstr($post));

        //echo $res . '<br/><br/>'; exit;
        $res = json_decode($res, true);

        if(!$res || empty($res)){
            $this->showmessage('获取数据失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $res['resp'] = json_decode(base64_decode($res['resp']), true);

        $code = $res['resp']['formaction'];

        if(!$code){
            if($res['resp']['respmsg']){
                $this->showmessage($res['resp']['respmsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = file_get_contents('php://input');

        //$p = "resp=eyJyZXN1bHRjb2RlIjoiMDAwMCIsInJlc3VsdG1zZyI6IuS6pOaYk%2baIkOWKn%2b%2b8gSIsInR4bmFtdCI6MTAwMCwibWVyaWQiOiI4OTkxMTkzNiIsIm9yZGVyaWQiOiIyMDE4MTIyMjEyMjE1NDE5MzQ4IiwicXVlcnlpZCI6IkgxMTkyMDE4MTIyMjEyMjE1MzU1ODE5MjY3IiwicGF5dGltZSI6IjIwMTgtMTItMjIgMTI6MjM6MTIifQ%3d%3d&sign=5626bc09d7936651618a4e3a1293f6c0";

        if(!$p){
            echo '';exit;
        }
        parse_str($p, $p);

        if(empty($p)){
            echo ''; exit;
        }

        /*
         * Array
(
    [resp] => eyJyZXN1bHRjb2RlIjoiMDAwMCIsInJlc3VsdG1zZyI6IuS6pOaYk+aIkOWKn++8gSIsInR4bmFtdCI6MTAwMCwibWVyaWQiOiI4OTkxMTkzNiIsIm9yZGVyaWQiOiIyMDE4MTIyMjEyMjE1NDE5MzQ4IiwicXVlcnlpZCI6IkgxMTkyMDE4MTIyMjEyMjE1MzU1ODE5MjY3IiwicGF5dGltZSI6IjIwMTgtMTItMjIgMTI6MjM6MTIifQ==
    [sign] => 5626bc09d7936651618a4e3a1293f6c0
)
         */

        $resp = $p['resp'];
        $p['resp'] = json_decode(base64_decode($p['resp']),true);

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['resp']['orderid'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['resp']['queryid']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['sign'];
        $sign2 = md5($resp . $this->config['signkey']);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['resp']['resultcode'] !== "0000"){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],"0000");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}